<template>
  <!-- 新增 & 编辑 弹窗 -->
  <a-modal
    v-model:visible="dialogVisible"
    width="840px"
    :title="`${dictValue ? dictValue : '字典'}数据管理`"
    :footer="false">
    <a-form
      ref="formRef"
      auto-label-width
      :model="formState"
      :rules="formRules"
      @submit="handleSubmit"
    >
      <a-table
        bordered
        row-key="id"
        :data="tableData"
        :loading="pageLoading"
        :pagination="pageData"
        :on-page-change="onPageChange"
      >
        <template #columns>
          <a-table-column title="数据名称" data-index="name">
            <template #cell="{ record }">
              <a-form-item v-if="record.id === formState.id" field="name">
                <a-input v-model="formState.name" placeholder="请输入数据名称"></a-input>
              </a-form-item>
              <span v-else>{{ record.name }}</span>
            </template>
          </a-table-column>
          <a-table-column title="数据值" data-index="name">
            <template #cell="{ record }">
              <a-form-item v-if="record.id === formState.id" field="value">
                <a-input v-model="formState.value" placeholder="请输入数据编码"></a-input>
              </a-form-item>

              <span v-else>{{ record.value }}</span>
            </template>
          </a-table-column>

          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <DictBadge :options="statusOptions" :value="record.status"/>
            </template>
          </a-table-column>
          <a-table-column title="排序" data-index="sort"></a-table-column>
          <a-table-column title="备注" data-index="remark"></a-table-column>
          <a-table-column title="操作" :width="160">
            <template #cell="{ record }">
              <a-button type="text" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm content="删除后不可恢复，确定要删除吗？" @ok="handleDelete(record)">
                <a-button type="text" status="danger">删除</a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>


        <template #value="{ record }">

        </template>

        <template #status="{ record, rowIndex }">
          <span v-if="record.id === formState.id">
            <a-switch
              v-model="formState.status"
              :checked-value="1"
              checked-text="启用"
              :unchecked-value="0"
              unchecked-text="停用"
            >
            <template #checked-icon>
              <icon-check />
            </template>

            <template #unchecked-icon>
              <icon-close />
            </template>
          </a-switch>
          </span>

          <span v-else>
          <a-switch
            v-model="tableData[rowIndex].status"
            :checked-value="1"
            checked-text="启用"
            :unchecked-value="0"
            unchecked-text="停用"
            @change="onStatusChange(record)"
          >
            <template #checked-icon>
              <icon-check />
            </template>

            <template #unchecked-icon>
              <icon-close />
            </template>
          </a-switch>
          </span>
        </template>

        <template #operations="{ record }">
          <span v-if="record.id === formState.id">
              <a-button type="text" html-type="submit">保存</a-button>
              <a-button type="text" @click="handleCancel()">取消</a-button>
          </span>
          <span v-else>
              <a-button type="text" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm content="删除后不可恢复，确定要删除吗？" @ok="handleDelete(record)">
                <a-button type="text" status="danger">删除</a-button>
              </a-popconfirm>
          </span>
        </template>
      </a-table>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import get from "lodash/get";
import { addDictData, delDictData, getDictDataList, updateDictData } from "@/api/system/dict";
import { statusOptions } from "@/enums/status";

export default defineComponent({
  data() {
    return {
      pageLoading: false,
      statusOptions,
      tableData: [],
      // 搜索表单
      dictId: undefined,
      dictValue: undefined,
      pageData: {
        pageSize: 50,
        current: 1,
        total: 0
      },
      searchForm: {
        name: "",
        status: ""
      },
      // 创建弹窗
      dialogVisible: false,
      formState: {
        id: undefined,
        name: undefined,
        value: undefined,
        sort: 10,
        status: 1,
        remark: undefined
      },
      formRules: {
        name: [{ required: true, min: 2, message: "至少2个字符", trigger: "change" }],
        value: [{ required: true, min: 2, message: "至少2个字符", trigger: "change" }],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }]
      }
    };
  },
  mounted() {
    // if (this.$route.query?.id) {
    //   this.searchForm.dict_id = Number(this.$route.query?.id);
    // }
    // this.fetchTableData();
  },
  methods: {
    handleOpen(record) {
      if (record.id) {
        this.dictId = record.id;
        this.dictValue = record.name;
        this.dialogVisible = true;
        this.fetchTableData();
      }
    },
    onPageChange(current: number) {
      this.fetchTableData({ current });
    },
    async fetchTableData(extraParam = {}) {
      this.pageLoading = true;
      try {
        let params = {
          ...this.pageData,
          ...this.searchForm,
          dict_id: this.dictId
        };
        if (extraParam) {
          params = {
            ...params,
            ...extraParam
          };
        }
        const { data, code } = await getDictDataList(params);

        if (code === 200 && data) {
          this.tableData = get(data, "list", []).map(item => {
            item.edit = false;
            return item;
          });
          this.pageData.current = data.current || 0;
          this.pageData.total = data.total || 0;
        }
      } catch (err) {
        console.warn(err);
        // Message.error("出了点小问题，请稍后重试！");
      }
      this.pageLoading = false;
    },
    handleSearch(current: number) {
      this.fetchTableData({ current });
    },
    // 修改状态
    onStatusChange(record){
      this.$message.success(`${record.name} - ${record.status}`)
      console.log(record)
    },
    // 操作
    handleDelete(rowData) {
      if (!rowData.id) return;

      delDictData(rowData).then(res => {
        const { code, msg } = res;

        if (code === 200) {
          this.$message.success(msg || "删除成功！");
          this.fetchTableData();
        } else {
          this.$message.error(msg || "出了点小问题，请稍后重试！");
        }
      });
    },
    // 创建表单
    handleEdit(rowData: any) {
      if (rowData.id) {
        if (rowData.id) {
          this.formState = {
            id: rowData.id,
            name: rowData.name,
            value: rowData.value,
            status: rowData.status,
            sort: rowData.sort,
            remark: rowData.remark
          };
        }
      }
    },
    handleCancel() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.formState = {
        id: undefined,
        name: undefined,
        value: undefined,
        sort: 10,
        status: 1,
        remark: undefined
      };
    },
    async handleSubmit({ values, errors }) {
      console.log("values:", values, "\nerrors:", errors);
      if (!errors) {
        this.pageLoading = true;

        try {
          const params = {
            ...this.formState
          };
          let result = {};
          if (params.id) {
            result = await updateDictData(params);
          } else {
            result = await addDictData(params);
          }
          const { msg } = result;

          this.$message.success(msg || "创建成功！");
          await this.fetchTableData();
          this.handleCancel();
        } catch (err) {
          // you can report use errorHandler or other
        } finally {
          this.pageLoading = false;

        }
      }
    }
  }
});
</script>


<style scoped lang="less">
.form-footer {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
